package com.example.smartretaildemo.module.classification.fragment;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import com.example.smartretaildemo.R;
import com.example.smartretaildemo.bean.classification.CommodityTypeInfo;
import com.example.smartretaildemo.databinding.FragmentClassificationBinding;
import com.example.smartretaildemo.module.classification.adapter.ClaRViewAdapter;
import com.example.smartretaildemo.module.classification.model.Commodity;
import com.example.smartretaildemo.module.classification.viewmodel.ClaViewModel;
import com.example.smartretaildemo.network.OkHttpUtils;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import okhttp3.Call;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ClassificationFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ClassificationFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private FragmentClassificationBinding binding;
    private List<Commodity> list = new ArrayList<>();
    public ClassificationFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ClassificationFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ClassificationFragment newInstance(String param1, String param2) {
        ClassificationFragment fragment = new ClassificationFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentClassificationBinding.inflate(inflater, container, false);
//        从缓存读取所选分类，若无默认缓存则为分类1
        SharedPreferences sp = getActivity().getSharedPreferences("calsList01", Context.MODE_PRIVATE);
        Set<String> claList = new HashSet<>();
        Set<String> sList=new HashSet<>();
        sList.add("1");
        List<String> cList = new ArrayList<>();
        claList = sp.getStringSet("cals", sList);
        for (String rood : claList) {
            cList.add(rood);
        }
        getActivity().getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.cla_title_bar);
//        异步取得所有商品
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpUtils.builder()
                        .url(ClaViewModel.COMMODITYGETALL)
                        .addParam("userId", "ODky")
                        .get()
                        .async(new OkHttpUtils.ICallBack() {
                            @Override
                            public void onSuccessful(Call call, String data) {
                                Gson gson = new Gson();
                                CommodityTypeInfo commodity = gson.fromJson(data, CommodityTypeInfo.class);
                                List<CommodityTypeInfo.DataBean> Temp = commodity.getData();
                                for (int i = 0; i < Temp.size(); i++) {
                                    String id = String.valueOf(Temp.get(i).getCommodityTypeId());
                                    for (String typeId : cList) {
//                                        Log.i("TAG", "id: " + id + ", typeId: " + typeId);
//                                        根据所选分类与每个商品的分类判断
                                        if (id.equals(typeId)) {
                                            list.add(new Commodity(Temp.get(i).getId(),
                                                    Temp.get(i).getCommodityName(),
                                                    id,
                                                    Temp.get(i).getMoney(),
                                                    Temp.get(i).getCostPrice(),
                                                    Temp.get(i).getPic(),
                                                    Temp.get(i).getVolume()));
                                        }
                                    }
                                }
//                                刷新UI控件
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        binding.rvCla.setLayoutManager(new LinearLayoutManager(getContext()));
                                        binding.rvCla.setAdapter(new ClaRViewAdapter(list, getContext(), getActivity().getWindowManager()));
                                    }
                                });
                            }

                            @Override
                            public void onFailure(Call call, String errorMsg) {

                            }
                        });
            }
        }).start();
        return binding.getRoot();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}